package com.sita.cfmoto.interact.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sita.cfmoto.R;
import com.sita.cfmoto.rest.model.Comment;
import com.sita.cfmoto.rest.model.Dynamic;
import com.sita.cfmoto.rest.model.Member;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.ui.view.ResizableImageView;
import com.sita.cfmoto.utils.InteractUtils;
import com.sita.cfmoto.utils.PersistUtils;
import com.sita.cfmoto.utils.ShareUtils;
import com.squareup.picasso.Picasso;
import com.umeng.socialize.utils.BitmapUtils;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by lijuan zhang on 2016/8/5.
 */
public class DynamicDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private OnItemClickListener itemClickListener;
    private OnLikeStatusChangedListener likeStatusChangedListener;
    private OnLikeMoreClickListener likeMoreClickListener;
    private List<Comment> commentData = new ArrayList<>();
    private List<Member> likeMemberData = new ArrayList<>();
    private Dynamic dynamic;
    private int DYNAMIC = 0;
    private int LIKE = 1;
    private int COMMENT = 2;
    private boolean isSelfLike = false;
    private LikeMemberListAdapter likeMemberListAdapter;
    private GridLayoutManager mGridLayoutManager;

    private Context context;
    private Activity activity;

    public DynamicDetailAdapter(Activity activity) {
        this.activity = activity;
        this.context = activity.getApplicationContext();
    }

    public void setDynamicDetailItem(Dynamic dynamic) {
        this.dynamic = dynamic;
        notifyItemRangeChanged(0, 2);
    }

    public void setLikeMemberData(List<Member> data) {
        likeMemberData.clear();
        likeMemberData.addAll(data);
        //判断自己是否点赞了
        isSelfLike = false;
        for (Member element : likeMemberData)
            if (element.userId.equals(String.valueOf(PersistUtils.getUsers().get(0).getAccountId()))) {
                isSelfLike = true;
            }
        notifyItemRangeChanged(0, 2);
    }

    public void setCommentData(List<Comment> data) {
        commentData.clear();
        commentData.addAll(data);
        notifyItemRangeChanged(0, data.size() + 2);
    }


    public void appendCommentData(List<Comment> data) {
        int currCount = getItemCount();
        this.commentData.addAll(data);
        notifyItemRangeInserted(currCount, data.size());
    }

    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public void setOnLikeStatusChangedListener(OnLikeStatusChangedListener likeStatusChangedListener) {
        this.likeStatusChangedListener = likeStatusChangedListener;
    }

    public void setOnLikeMoreClickListener(OnLikeMoreClickListener likeMoreClickListener) {
        this.likeMoreClickListener = likeMoreClickListener;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        if (viewType == DYNAMIC) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dynamic_detail, parent, false);
            return new DynamicViewHolder(view);
        } else if (viewType == LIKE) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dynamic_like, parent, false);
            return new LikeViewHolder(view);
        } else if (viewType == COMMENT) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment_recycler, parent, false);
            return new CommentViewHolder(view);
        }
        return null;
    }


    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return DYNAMIC;
        } else if (position == 1) {
            return LIKE;
        } else {
            return COMMENT;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof DynamicViewHolder) {
            Picasso.with(GlobalContext.getGlobalContext()).load(dynamic.accountIdAvat).centerCrop().placeholder(R.drawable.default_head_icon).fit()
                    .into(((DynamicViewHolder) holder).userAvatar);
            if (dynamic.source == 0) {
                Picasso.with(GlobalContext.getGlobalContext()).load((dynamic.picList == null || dynamic.picList.size() == 0 ? null : dynamic.picList.get(0))).centerCrop()
                        .placeholder(R.drawable.dynamic_default_icon).fit()
                        .into(((DynamicViewHolder) holder).dynamicImg);
            } else if (dynamic.source == 1) {
                Picasso.with(GlobalContext.getGlobalContext()).load((dynamic.picList == null || dynamic.picList.size() == 0 ? null : dynamic.picList.get(0)))
                        .placeholder(R.drawable.official_dynamic_default_icon)
                        .into(((DynamicViewHolder) holder).dynamicImg);
            }

            ((DynamicViewHolder) holder).userName.setText(dynamic.accountIdNickname);
            ((DynamicViewHolder) holder).share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String title = context.getString(R.string.dynamic_share);
                    String content = ((DynamicViewHolder) holder).dynamicContent.getText().toString();
                    String url = dynamic.picList.get(0);
                    Bitmap bitmap = ((BitmapDrawable) ((DynamicViewHolder) holder).dynamicImg.getDrawable()).getBitmap();
                    if (bitmap != null) {
                        ShareUtils.doSharePost(dynamic.msgId,
                                BitmapUtils.compressBitmap(BitmapUtils.bitmap2Bytes(bitmap), 24 * 1024),
                                title, content, context, activity);
                    } else {
                        ShareUtils.doSharePost(dynamic.msgId, url, title, content, context, activity);
                    }
                }
            });
            ((DynamicViewHolder) holder).dynamicTime.setText(dynamic.createTime);
            ((DynamicViewHolder) holder).dynamicContent.setText(dynamic.content);
            ((DynamicViewHolder) holder).dynamicLocation.setText(dynamic.address);
            //应该根据获取的动态数和点赞数设置
            ((DynamicViewHolder) holder).likeNum.setText(String.valueOf(likeMemberData.size()));
            ((DynamicViewHolder) holder).commentNum.setText(String.valueOf(dynamic.commentCount));
            if (isSelfLike) {
                ((DynamicViewHolder) holder).likeImg.setImageResource(R.drawable.like_select);
            } else {
                ((DynamicViewHolder) holder).likeImg.setImageResource(R.drawable.like_unselect);
            }
            ((DynamicViewHolder) holder).likeBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //判断当前用户的点赞状态
                    long accountId = PersistUtils.getUsers().get(0).getAccountId();
                    long resId = Long.parseLong(dynamic.msgId);
                    if (!isSelfLike) {
                        InteractUtils.releaseLike(accountId, resId, new InteractUtils.ReleaseLikeCallback() {
                            @Override
                            public void onLikeReleased(boolean b) {
                                if (likeStatusChangedListener != null) {
                                    likeStatusChangedListener.onLikeStatusChanged(b);
                                }
                            }
                        });
                    } else {
                        InteractUtils.releaseUnLike(accountId, resId, new InteractUtils.ReleaseUnLikeCallback() {
                            @Override
                            public void onUnLikeReleased(boolean b) {
                                if (likeStatusChangedListener != null) {
                                    likeStatusChangedListener.onLikeStatusChanged(b);
                                }
                            }
                        });
                    }
                }
            });
        } else if (holder instanceof LikeViewHolder) {
            if (dynamic.commentCount == 0) {
                ((LikeViewHolder) holder).divider.setVisibility(View.GONE);
            } else {
                ((LikeViewHolder) holder).divider.setVisibility(View.VISIBLE);
            }
            ((LikeViewHolder) holder).likeCount.setText(GlobalContext.getGlobalContext().getString(R.string.like_detail_count, String.valueOf(likeMemberData.size())));
            ((LikeViewHolder) holder).commentCount.setText(GlobalContext.getGlobalContext().getString(R.string.comment_detail_count, String.valueOf(dynamic.commentCount)));
            //设置点赞列表
            initLikeList(((LikeViewHolder) holder).likeRecycler);
            likeMemberListAdapter.setData(likeMemberData.size() > 4 ? likeMemberData.subList(0, 4) : likeMemberData);

            ((LikeViewHolder) holder).likeMemberMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    likeMoreClickListener.onLikeMoreClick(likeMemberData);
                }
            });

        } else if (holder instanceof CommentViewHolder) {
            //数据绑定
            Comment comment = commentData.get(position - 2);
            ((CommentViewHolder) holder).commentatorContent.setText(comment.message);
            ((CommentViewHolder) holder).commentatorName.setText(comment.nickName);
            ((CommentViewHolder) holder).commentatorTime.setText(comment.createTime);
            Picasso.with(GlobalContext.getGlobalContext())
                    .load(comment.avatar).centerCrop()
                    .placeholder(R.drawable.dynamic_default_icon).fit()
                    .into(((CommentViewHolder) holder).commentatorIcon);
            ((CommentViewHolder) holder).commentItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (itemClickListener != null)
                        itemClickListener.onItemClick(v, position, comment);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        //返回数据长度
        return commentData.size() + 2;
    }

    private void initLikeList(RecyclerView recyclerView) {
        mGridLayoutManager = new GridLayoutManager(GlobalContext.getGlobalContext(), 4);
        recyclerView.setLayoutManager(mGridLayoutManager);
        recyclerView.setItemAnimator(null);
        likeMemberListAdapter = new LikeMemberListAdapter();
        recyclerView.setAdapter(likeMemberListAdapter);
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position, Comment comment);
    }

    public interface OnLikeStatusChangedListener {
        void onLikeStatusChanged(boolean isChanged);
    }

    public interface OnLikeMoreClickListener {
        void onLikeMoreClick(List<Member> memberList);
    }

    //评论布局
    public class CommentViewHolder extends RecyclerView.ViewHolder {
        public RelativeLayout commentItem;
        public CircleImageView commentatorIcon;
        public TextView commentatorName;
        public TextView commentatorContent;
        public TextView commentatorTime;

        public CommentViewHolder(View view) {
            super(view);
            commentItem = (RelativeLayout) view.findViewById(R.id.item_comment_layout);
            commentatorIcon = (CircleImageView) view.findViewById(R.id.comment_icon);
            commentatorName = (TextView) view.findViewById(R.id.comment_name);
            commentatorContent = (TextView) view.findViewById(R.id.comment_content);
            commentatorTime = (TextView) view.findViewById(R.id.comment_time);
        }
    }

    //动态详情
    public class DynamicViewHolder extends RecyclerView.ViewHolder {
        public CircleImageView userAvatar;
        public TextView userName;
        public TextView dynamicTime;
        public TextView dynamicContent;
        public ResizableImageView dynamicImg;
        public TextView likeNum;
        public TextView commentNum;
        public ImageView share;
        public TextView dynamicLocation;
        public LinearLayout likeBtn;
        public ImageView likeImg;

        public DynamicViewHolder(View view) {
            super(view);
            userAvatar = (CircleImageView) view.findViewById(R.id.user_avatar);
            userName = (TextView) view.findViewById(R.id.user_name);
            dynamicTime = (TextView) view.findViewById(R.id.dynamic_time);
            dynamicContent = (TextView) view.findViewById(R.id.dynamic_content_txt);
            dynamicImg = (ResizableImageView) view.findViewById(R.id.dynamic_content_img);
            likeNum = (TextView) view.findViewById(R.id.like_num);
            commentNum = (TextView) view.findViewById(R.id.comment_num);
            share = (ImageView) view.findViewById(R.id.share);
            dynamicLocation = (TextView) view.findViewById(R.id.dynamic_location);
            likeBtn = (LinearLayout) view.findViewById(R.id.like_btn);
            likeImg = (ImageView) view.findViewById(R.id.like_img);
        }
    }

    public class LikeViewHolder extends RecyclerView.ViewHolder {
        public TextView likeCount;
        public TextView commentCount;
        public RecyclerView likeRecycler;
        public ImageView likeMemberMore;
        private View divider;

        public LikeViewHolder(View view) {
            super(view);
            likeCount = (TextView) view.findViewById(R.id.like_detail_count);
            commentCount = (TextView) view.findViewById(R.id.comment_detail_count);
            likeRecycler = (RecyclerView) view.findViewById(R.id.like_detail_recycler);
            likeMemberMore = (ImageView) view.findViewById(R.id.like_member_more);
            divider = view.findViewById(R.id.divider);
        }
    }
}
